package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Async
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {
    @Autowired
    private IScheduleClient scheduleClient;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    /**
     * 添加任务到延迟队列中
     *
     * @param id          文章的id
     * @param publishTime 发布的时间  可以做为任务的执行时间
     */
    @Override
    public void addNewsToTask(Integer id, Date publishTime) {
        log.info("添加任务到延迟服务中----begin");

        Task task = new Task();
        task.setExecuteTime(publishTime.getTime());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        WmNews wmNews = new WmNews();
        wmNews.setId(id);
        task.setParameters(ProtostuffUtil.serialize(wmNews));
        scheduleClient.addTask(task);

        log.info("添加任务到延迟服务中----end");
    }

    /**
     * 消费延迟队列数据
     * 要获取文章id
     * poll后的ResponseResult中data为task
     * 将data（即task）-->json数据 --> task对象
     * task中getParameters为wmNews对象，wmNews对象中包含文章id
     * task.getParameters->工具类ProtostuffUtil ->wmNews
     * 获取wmNews中的id，进行文章审核
     */
    @Override
    @Scheduled(fixedRate = 1000)    //每一秒拉取一次任务
    public void scanNewsByTask() {
        //拉取任务
        ResponseResult result = scheduleClient.poll(TaskTypeEnum.REMOTEERROR.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        //参数校验
        if (result.getCode() == 200 && result.getData() != null) {
            Task task = JSON.parseObject(JSON.toJSONString(result), Task.class);
            WmNews wmNews = ProtostuffUtil.deserialize(task.getParameters(), WmNews.class);
            wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        }
    }
}
